package com.feng.aop.config;

import com.mchange.v2.c3p0.ComboPooledDataSource;
import org.springframework.context.EmbeddedValueResolverAware;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import org.springframework.util.StringValueResolver;

import javax.sql.DataSource;
import java.beans.PropertyVetoException;
//开启事务
@EnableTransactionManagement
@PropertySource("classpath:/db.properties")
@Configuration
@ComponentScan(value = "com.feng.aop")
public class TransactionConfig  implements EmbeddedValueResolverAware {

    private  StringValueResolver resolver;
    //用方法为变量赋值不能放在属性上
    /**
     * 建立数据源
     * @return
     */
    @Bean
    public DataSource dataSource() throws PropertyVetoException {
        String name = resolver.resolveStringValue("${db.name}");
        String password = resolver.resolveStringValue("${db.password}");
        String url = resolver.resolveStringValue("${db.url}");
        String driver = resolver.resolveStringValue("${db.driver}");
        ComboPooledDataSource dataSource = new ComboPooledDataSource();
        dataSource.setUser(name);
        dataSource.setPassword(password);
        dataSource.setJdbcUrl(url);
        resolver.resolveStringValue(driver);
        System.out.println(1);
        return  dataSource;
    }

    /**
     *  JdbcTemplate 来操作数据库
     * @return
     */
    //此处的参数  spring容器会自动寻找对应的bean注入
    @Bean
    public JdbcTemplate jdbcTemplate( DataSource dataSource){

       return   new JdbcTemplate(dataSource);

    }


    /**
     * 配置事务管理器
     * @param
     * @return
     */
    @Bean
    public PlatformTransactionManager transactionManager() throws PropertyVetoException {
        return new DataSourceTransactionManager(dataSource());
    }

    @Override
    public void setEmbeddedValueResolver(StringValueResolver resolver) {
        this.resolver=resolver;
    }


}
